import { defineComponent, ref, onMounted, watch } from 'vue';
import './basic-table.scss';
import { ElTable } from 'element-plus';
export default defineComponent({
  // 接收参数
  props: {
    operateOptions: {
      type: Array,
      default: () => [],
    },
    columns: {
      type: Array,
      default: () => [],
    },
    data: {
      type: Array,
      default: () => [],
    },

    tableOptions: {
      type: Object,
      default: () => {},
    },
    tableEvents: {
      type: Object,
      default: () => {},
    },

    pagination: {
      type: Object,
      default: () => ({
        pageSizes: [10, 20, 30, 50, 100],
        layout: 'total, sizes, prev, pager, next',
        total: 1000,
      }),
    },
  },
  emits: ['loadTableData'],
  setup(props, context) {
    const { columns, tableEvents, pagination, tableOptions, operateOptions } = props;

    const { slots } = context;

    const selection = ref(false);
    const indexColumn = ref(false);
    const indexWidth = ref('50');
    const indexMethod = ref(null);

    const { emit } = context;

    onMounted(() => {
      handleColumns();
      handleTableData();
      handlePagination();
    });
    const handlePagination = () => {
      insidePagination.value = Object.assign(insidePagination.value, pagination);
    };
    watch(
      () => props.data,
      () => {
        handleTableData();
      },
    );
    watch(() => props.columns, () => {
      handleColumns();
    });

    const insideColumns = ref([]);
    const supportOption = ref({
      show: false,
      items: [],
      width: '124px',
      minWidth: '124px',
    });
    const handleColumns = () => {
      // 转换vue3 语法
      insideColumns.value = columns
        .map((item) => {
          let res;
          switch (item.type) {
            case 'option':
              supportOption.value.show = true;
              supportOption.value.items = item.items;
              supportOption.value.minWidth = item.minWidth;
              supportOption.value.width = item.width;
              break;
            case 'selection':
              selection.value = true;
              break;
            case 'index':
              indexColumn.value = true;
              return undefined;
            default:
              res = item;
              break;
          }
          return res;
        })
        .filter(Boolean);
    };

    const insideTableData = ref([]);
    // 处理表格数据
    const handleTableData = () => {
      const { data } = props;
      insideTableData.value = data.concat([]);
      console.log(insideTableData.value, data, 'insideTableData.value');
    };

    const onLoadTableData = () => {
      const pagination = {
        page: insidePagination.value.currentPage,
        pageSize: insidePagination.value.pageSize,
      };

      emit('loadTableData', pagination);
    };

    const render = () => (
      <>
        <div className="operate-wrap">{renderOperate()}</div>
        <div class="app-container container-table">{renderTable()}</div>
        {renderPagination()}
      </>
    );
    // 构建操作栏
    const renderOperate = () => (
      <div class="operate">
        {operateOptions.map((item, idx) => (
          <el-button
            key={idx}
            type={item.type}
            icon={item.icon}
            onClick={() => item.click()}
            size={item.size}
            class={item.class}
          >
            {item.label}
          </el-button>
        ))}
      </div>
    );

    const renderTable = () => {
      const on = {};
      if (tableEvents) {
        Object.keys(tableEvents).forEach((key) => {
          const selfKey = transformStr(`on-${key}`);
          on[selfKey] = tableEvents[key];
        });
      }
      return (
        <ElTable
          data={insideTableData.value}
          size="small"
          class="basic-table"
          style="width: 100%"
          tooltip-effect="light"
          {...on}
          {...tableOptions}
        >
          {renderColumns()}
        </ElTable>
      );
    };
    const transformStr = (str) => {
      const re = /-(\w)/g;
      return str.replace(re, ($0, $1) => $1.toUpperCase());
    };
    const renderColumns = () => (
      <>
        {renderSelection()}
        {renderIndexColumn()}
        {renderTableColumn()}
        {renderOptionColumn()}
      </>
    );
    const renderSelection = () => {
      if (selection.value) {
        return <el-table-column type="selection" width="50" align="center"></el-table-column>;
      }
    };
    const renderIndexColumn = () => {
      if (indexColumn.value) {
        return (
          <el-table-column
            label="序号"
            type="index"
            width={indexWidth.value}
            index={indexMethod.value}
            align="center"
          ></el-table-column>
        );
      }
    };
    const renderTableColumn = () => (
      <>
        {insideColumns.value.map((column, idx) => (
          <el-table-column key={idx} label={column.label} prop={column.prop} type={column.type} {...column.options}>
            {{ default: scope => slots[column.slot]?.(scope) }}
          </el-table-column>
        ))}
      </>
    );
    const renderOptionColumn = () => {
      if (supportOption.value.show) {
        return (
          <el-table-column
            align="left"
            class="box"
            label="操作"
            min-width={supportOption.value.minWidth || '124px'}
            width={supportOption.value.width}
          >
            {{
              default: scope => (
                <div class="option-wrap">
                  {supportOption.value.items.map((item, idx) => (
                    <span key={idx} class="option-item">
                      <el-tooltip placement="bottom" key={idx} content={item.label} disabled={!!item.text}>
                        {renderOptions(item, scope)}
                      </el-tooltip>
                    </span>
                  ))}
                </div>
              ),
            }}
          </el-table-column>
        );
      }
    };

    const renderOptions = (item, scope) => {
      // 添加二次确认框
      // confirm: {
      //   title: '提示',
      //   content: '是否删除？',
      //   ok: () => {
      //     console.log('ok');
      //   },
      //   cancel: () => {
      //     console.log('cancel');
      //   },
      // },
      //   <el-popconfirm
      //   width="220"
      //   confirm-button-text="OK"
      //   cancel-button-text="No, Thanks"
      //   :icon="InfoFilled"
      //   icon-color="#626AEF"
      //   title="Are you sure to delete this?"
      // >
      //   <template #reference>
      //     <el-button>Delete</el-button>
      //   </template>
      // </el-popconfirm>
      let el = null;
      if (item.confirm) {
        const { confirm } = item;
        el = (
          <span>
            <el-popconfirm
              width="220"
              confirm-button-text={confirm.okText || '确定'}
              cancel-button-text={confirm.cancelText || '取消'}
              icon-color="#626AEF"
              title={item.confirm.content}
              onConfirm={() => item.confirm.ok(scope.row)}
              onCancel={() => item.confirm.cancel(scope.row)}
            >
              {{
                reference: () => (
                  <i
                    class={['opt-icon option-text cur', item.disabled && item.disabled(item) ? 'is-disabled' : null]}
                    title={item.text}
                  >
                    {item.text + 111}
                  </i>
                ),
              }}
            </el-popconfirm>
          </span>
        );
        console.log(el, 'if');
        return el;
      }
      el = (
        <i
          onClick={() => item.click(scope.row)}
          class={['opt-icon option-text cur', item.disabled && item.disabled(item) ? 'is-disabled' : null]}
          title={item.text}
        >
          {item.text}
        </i>
      );
      return el;
    };

    const insidePagination = ref({
      pageSizes: [10, 20, 30, 50, 100],
      pagerCount: 5,
      layout: 'total, sizes, prev, pager, next',
      total: 1000,
      pageSize: 10,
      currentPage: 1,
      sizeChange: () => {
        // insidePagination.value.pageSize = value;
        onLoadTableData();
      },
      currentChange: () => {
        onLoadTableData();
      },
      prevClick: () => {
        onLoadTableData();
      },
      nextClick: () => {
        onLoadTableData();
      },
    });

    const renderPagination = () => (
      <div class="pagination-wrap">
        <el-pagination
          v-model:page-size={insidePagination.value.pageSize}
          page-sizes={insidePagination.value.pageSizes}
          pagerCount={insidePagination.value.pagerCount}
          layout={insidePagination.value.layout}
          total={insidePagination.value.total}
          onSizeChange={insidePagination.value.sizeChange}
          onCurrentChange={insidePagination.value.currentChange}
          v-model:currentPage={insidePagination.value.currentPage}
          onPrevClick={insidePagination.value.preClick}
          onNextClick={insidePagination.value.nextClick}
        />
      </div>
    );

    return render;
  },
});
